import {
  Component,
  EventEmitter,
  Injector,
  Input,
  OnInit,
  Output,
} from '@angular/core';
import {
  GetDataComboItemDtoOfInt64,
  ArticleSourceInfoServiceProxy,
} from '@abp/service-proxies/service-proxies';
import { AppComponentBase } from '@abp/components';

@Component({
  selector: 'article-source-combo',
  templateUrl: './article-source-combo.component.html',
  styles: [],
})
export class ArticleSourceComboComponent extends AppComponentBase
  implements OnInit {
  articleSources: GetDataComboItemDtoOfInt64[] = [];
  @Input() placeholder: string;
  @Input() selectedArticleSource: GetDataComboItemDtoOfInt64 = undefined;
  @Output() selectedArticleSourceChange: EventEmitter<
    GetDataComboItemDtoOfInt64
  > = new EventEmitter<GetDataComboItemDtoOfInt64>();
  @Input() isFindRoot: boolean;

  private _articleSourceId: number;
  @Input() articleSourceId: number;

  constructor(
    private _articleSourceService: ArticleSourceInfoServiceProxy,
    injector: Injector,
  ) {
    super(injector);
  }

  ngOnChanges(): void {
    this._articleSourceService
      .getArticleSoruceComboItems()
      .subscribe(result => {
        this.articleSources = result;
        this._articleSourceId = this.articleSourceId;
        this.autoSelect();
      });
  }

  ngOnInit(): void {}

  autoSelect() {
    if (!this.articleSources || !this._articleSourceId) {
      return;
    }
    this.selectedArticleSource = this.articleSources.find(
      item => item.value == this._articleSourceId,
    );
    if (this.selectedArticleSourceChange) {
      this.selectedArticleSourceChange.emit(this.selectedArticleSource);
    }
  }
}
